import tkinter as tk
from tkinter import messagebox, DISABLED
import os, re
import requests
from tkinter.filedialog import askdirectory


class Baidu():
    def __init__(self):
        self.repage = 0

    # 定义一个文件路径选择的方法
    def root(self):
        path_ = askdirectory()
        path.set(path_)

    # 定义一个btnserach按钮事件的方法
    def click(self):
        keyword = entword.get()
        root = entroot.get()
        page = entpage.get()
        if keyword == '':
            tk.messagebox.showinfo('警告', message='你还没有输入关键词')
        else:
            if root == '':
                tk.messagebox.showinfo('警告', message='你还没有选择保存路径')
            else:
                if page == '':
                    tk.messagebox.showinfo('警告', message='你还没有输入想要下载的页数')
                else:
                    if not page.isdigit():
                        tk.messagebox.showinfo('警告', message='请输入数字')
                    else:
                        root = root + '/' + keyword
                        tk.messagebox.showinfo('成功', message='点击确定,等待图片下载,下载过程中请勿关闭窗口,下载结束会自动关闭')

                        # 将返回值
                        self.rekeyword = keyword
                        self.reroot = root
                        self.repage = page

                        # 调用save方法
                        self.save()
                        # 关闭窗口
                        window.quit()

    def close(self):
        self.repage = 0
        # 关闭窗口
        window.quit()

    # 定义保存路径和文件夹的方法
    def save(self):
        if os.path.exists('{}'.format(self.reroot)) is False:
            os.mkdir(self.reroot)

    def images(self, url, path):
        # 添加请求头
        headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4315.5 Safari/537.36',
        }

        # 发送请求
        req = requests.get(url, headers=headers)

        # 保存源文件
        html = req.text

        # 匹配图片格式
        images = re.findall('"thumbURL":"(.*?)"', html, re.S)

        # 循环输入image
        for index, image in enumerate(images):
            req = requests.get(image)
            # 动态拼接图片文件名
            file = '{}{}'.format(self.rekeyword, image.split(',')[-1].split('&')[0])
            with open('{}/'.format(path) + file + '.jpg', 'wb') as f:
                f.write(req.content)


if __name__ == '__main__':
    # 实例化一个Baidu类
    baidu = Baidu()

    # 创建一个窗口
    window = tk.Tk()

    # 设置窗口标题
    window.title('下载器')

    # 设置窗口大小
    window.geometry('500x300')

    # 创建按钮,并且将按钮放到窗口里面,text给按钮设置名字
    labtitle = tk.Label(window, text='百度图片批量下载器', font=("微软雅黑", 18))
    labword = tk.Label(window, text='请输入关键词：')
    entword = tk.Entry(window)
    labroot = tk.Label(window, text='请选择保存路径：')
    path = tk.StringVar()
    entroot = tk.Entry(window, textvariable=path, state=DISABLED)
    btnroot = tk.Button(window, text="路径选择", command=baidu.root)
    labpage = tk.Label(window, text='请选择下载页数：')
    entpage = tk.Entry(window)
    btnserach = tk.Button(window, text='开始下载', command=baidu.click)
    btnexit = tk.Button(window, text='    退出    ', command=baidu.close)

    # 给按钮布局到窗口的哪个地方
    labtitle.place(x=140, y=20)

    labword.place(x=100, y=70)
    entword.place(x=200, y=70)

    labroot.place(x=100, y=120)
    entroot.place(x=200, y=120)
    btnroot.place(x=350, y=115)

    labpage.place(x=100, y=170)
    entpage.place(x=200, y=170)

    btnserach.place(x=150, y=240)
    btnexit.place(x=250, y=240)

    # 显示窗口
    window.mainloop()

	# 下载的页数
    for i in range(1, int(baidu.repage) + 1):
        url = 'https://image.baidu.com/search/acjson?' \
              'tn=resultjson_com&logid=11634671260851425331&ipn=rj' \
              '&ct=201326592&is=&fp=result&queryWord={}&cl=2&lm=-1' \
              '&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=&hd=&latest=&copyright=' \
              '&word={}&s=&se=&tab=&width=&height=&face=0&istype=2' \
              '&qc=&nc=1&fr=&expermode=&force=&pn={}&rn=30&gsm={}e&1607738339848='.format(baidu.rekeyword,
                                                                                          baidu.rekeyword,
                                                                                          i * 30, i)
        baidu.images(url, baidu.reroot)

